package com.smartrodin.springbootrabbitmq.config.mybatisplus;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * @author arnold_nie
 * @Date: Created in 2019-08-09 02:26 PM
 * @description: 批量新增数据 全字段插入
 */
public class InsertAllBatch extends AbstractMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        final String sql = SqlMethod.INSERT_ONE.getSql();
        final String fieldSql = prepareFieldSql( tableInfo );
        final String valueSql = prepareValuesSqlForMysqlBatch( tableInfo );
        final String sqlResult = String.format( sql, tableInfo.getTableName(), fieldSql, valueSql );
        SqlSource sqlSource = languageDriver.createSqlSource( configuration, sqlResult, modelClass );
        return this.addInsertMappedStatement( mapperClass, modelClass, "insertAllBatch", sqlSource, new NoKeyGenerator(), null, null );
    }

    private String prepareFieldSql(TableInfo tableInfo) {
        StringBuilder fieldSql = new StringBuilder();
        if (null != tableInfo.getKeyColumn()) {
            fieldSql.append( tableInfo.getKeyColumn() ).append( "," );
        }
        tableInfo.getFieldList().forEach( x -> {
            fieldSql.append( x.getColumn() ).append( "," );
        } );
        fieldSql.delete( fieldSql.length() - 1, fieldSql.length() );
        fieldSql.insert( 0, "(" );
        fieldSql.append( ")" );
        return fieldSql.toString();
    }

    private String prepareValuesSqlForMysqlBatch(TableInfo tableInfo) {
        final StringBuilder valueSql = new StringBuilder();
        valueSql.append( "<foreach collection=\"list\" item=\"item\" index=\"index\" open=\"(\" separator=\"),(\" close=\")\">" );
        if (null != tableInfo.getKeyProperty()) {
            valueSql.append( "#{item." ).append( tableInfo.getKeyProperty() ).append( "}," );
        }
        tableInfo.getFieldList().forEach( x -> valueSql.append( "#{item." ).append( x.getProperty() ).append( "}," ) );
        valueSql.delete( valueSql.length() - 1, valueSql.length() );
        valueSql.append( "</foreach>" );
        return valueSql.toString();
    }
}
